package com.example.audiorecorddemo;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.audiorecorddemo.dialog.PermissionDialog;
import com.example.audiorecorddemo.utils.AudioManagerUtils;
import com.example.audiorecorddemo.utils.StringUtils;
import com.tbruyelle.rxpermissions3.Permission;
import com.tbruyelle.rxpermissions3.RxPermissions;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

public class MainActivity extends AppCompatActivity {
    private Button btnRecord, btnPlay, btnStop;
    private SeekBar seekBar;
    private TextView textView;
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            3, 5,
            1, TimeUnit.MINUTES,
            new LinkedBlockingDeque<>(10),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());
    private String[] permissions = null;
    private PermissionDialog mPermissionDialog = null;
    private final String TAG = MainActivity.this.getClass().getSimpleName();
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            int recordTime = msg.what;
            LogUtils.d(TAG, "===录音时间为===" + recordTime);
            if (recordTime == 100) {
                stopTimeTask();
            }
            seekBar.setProgress(recordTime);
            textView.setText(recordTime/10  + "s");
        }
    };
    private Timer timer = new Timer();
    private TimerTask timerTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestBasicPermission();
        initView();
    }

    private void initTimeTask() {
        timer = new Timer();
        timerTask = new TimerTask() {
            int secondTime = 0;
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = secondTime++;
                        mHandler.sendMessage(message);
                    }
                });
            }
        };
        timer.schedule(timerTask, 0, 100);
    }

    private void stopTimeTask() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        AudioManagerUtils.getInstance().stopRecord();
    }

    private void requestBasicPermission() {
        final RxPermissions rxPermissions = new RxPermissions(this);
        StringBuilder rationaleSb = new StringBuilder();
        StringBuilder deniedSb = new StringBuilder();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions = new String[]{
                    Manifest.permission.READ_MEDIA_AUDIO,
                    Manifest.permission.READ_MEDIA_VIDEO,
                    Manifest.permission.READ_MEDIA_IMAGES,
                    Manifest.permission.RECORD_AUDIO,
            };
        } else {
            permissions = new String[]{
                    Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE,};
        }
        rxPermissions.requestEach(permissions).subscribe(new Observer<Permission>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
            }

            @Override
            public void onNext(@NonNull Permission permission) {
                if (permission.granted) {
                    LogUtils.d(TAG, "权限：" + permission.name + " 已开启");
                } else if (permission.shouldShowRequestPermissionRationale) {
                    LogUtils.d(TAG, "权限：" + permission.name + " 权限拒绝，但没有选中 不再询问");
                    if (rationaleSb.toString().contains(StringUtils.getPermissionName(MainActivity.this, permission.name))) {
                        return;
                    }
                    rationaleSb.append(StringUtils.getPermissionName(MainActivity.this, permission.name));
                    rationaleSb.append("、");
                } else {
                    LogUtils.d(TAG, "权限：" + permission.name + " 权限拒绝，并且选中 不再询问");
                    if (deniedSb.toString().contains(StringUtils.getPermissionName(MainActivity.this, permission.name))) {
                        return;
                    }
                    deniedSb.append(StringUtils.getPermissionName(MainActivity.this, permission.name));
                    deniedSb.append("、");
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                LogUtils.d(TAG, "permission  onError");
            }

            @Override
            public void onComplete() {
                if (TextUtils.isEmpty(rationaleSb) && TextUtils.isEmpty(deniedSb)) {
                    LogUtils.d(TAG, "permission.name ,权限已经允许");
                    startAudioRecord();
                } else {
                    if (!TextUtils.isEmpty(deniedSb)) {
                        showPermissionDialog(deniedSb, 0);
                    } else if (!TextUtils.isEmpty(rationaleSb)) {
                        showPermissionDialog(rationaleSb, 1);
                    }
                }
            }
        });
    }

    private void showPermissionDialog(StringBuilder permissionName, int permissionType) {
        if (null != mPermissionDialog && mPermissionDialog.isShowing()) {
            mPermissionDialog.dismiss();
            mPermissionDialog = null;
        }
        if (0 == permissionType) {
            mPermissionDialog = new PermissionDialog(MainActivity.this,
                    "请授权相关权限以确保相关功能能正常运行：" + permissionName
                            .toString().substring(0, permissionName.length() - 1), PermissionDialog.BUTTON_RIGHT_FLAG,
                    "确定", "知道了",
                    null, this::startAudioRecord);
            mPermissionDialog.show();
        } else if (1 == permissionType) {
            mPermissionDialog = new PermissionDialog(MainActivity.this,
                    "请授权相关权限以确保相关功能能正常运行：" + permissionName
                            .toString().substring(0, permissionName.length() - 1), PermissionDialog.BUTTON_RIGHT_FLAG,
                    "取消", "知道了",
                    null, this::startAudioRecord);
            mPermissionDialog.show();
        }
    }

    private void initView() {
        btnRecord = findViewById(R.id.btn_record);
        btnPlay = findViewById(R.id.btn_play);
        btnStop = findViewById(R.id.btn_stop);
        seekBar = findViewById(R.id.seekBar);
        textView = findViewById(R.id.tv_timer);
        btnRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtils.showShort("开始录音");
                buttonEnabled(false, true, true);
                startAudioRecord();
                initTimeTask();
            }
        });

        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AudioManagerUtils.getInstance().playPcm(true);
                buttonEnabled(false, false, true);
            }
        });
        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtils.showShort("停止录音");
                buttonEnabled(true, true, false);
                stopTimeTask();
            }
        });
    }

    private void startAudioRecord() {
        threadPoolExecutor.execute(() -> {
            AudioManagerUtils.getInstance().startRecord(new WeakReference<>(getApplicationContext()));
        });
    }

    private void buttonEnabled(boolean record, boolean play, boolean stop) {
        btnRecord.setEnabled(record);
        btnPlay.setEnabled(play);
        btnStop.setEnabled(stop);
    }

    @Override
    protected void onStop() {
        super.onStop();
        AudioManagerUtils.getInstance().pauseAudio();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AudioManagerUtils.getInstance().releaseAudio();
        stopTimeTask();
    }
}